﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SaiLing.Domain;
using SaiLing.Domain.Specification;
using SaiLing.Exceptions;
using SaiLing.Paging;
using SaiLing.SingleSignOn.Application.Service.Interfaces.System;
using SaiLing.SingleSignOn.Domain.Entities.System;
using SaiLing.SingleSignOn.Domain.Interfaces.System;
using SaiLing.SingleSignOn.Domain.Specifications.System;
using System.Linq;

namespace SaiLing.SingleSignOn.Application.Service.Providers.System
{
    public class ApplicationService : BaseService<Domain.Entities.System.Application>, IApplicationService
    {
        public ApplicationService(IUnitOfWork unitOfWork, IApplicationRepository repository) : base(unitOfWork, repository)
        {
        }

        public  Task<PageData<Domain.Entities.System.Application>> PageList(int pageIndex, int pageSize, string name)
        {
            var spec=new ApplicationSpecification(name,null);
            return GetMany(spec).ToPageData(pageIndex, pageSize);
        }

        public Task<IEnumerable< Domain.Entities.System.Application>> List(string name,string appkey)
        {
            var spec = new ApplicationSpecification(name, appkey);
            return Task.FromResult(GetMany(spec));
        }

        public async Task<int> Create(Domain.Entities.System.Application entity)
        {
            if (await ExistsAsync(new DirectSpecification<Domain.Entities.System.Application>(x => x.AppKey == entity.AppKey || x.Name == entity.Name)))
                throw new SaiLingException("应用名重复");
            await Add(entity);
            return await SaveChangesAsync();
        }

        public async Task<int> Edit(Domain.Entities.System.Application entity)
        {
            if (await ExistsAsync(new DirectSpecification<Domain.Entities.System.Application>(x => x.Id != entity.Id && x.Name == entity.Name)))
                throw new SaiLingException("应用名重复");
            Update(entity,
                x=>x.Name,
                x=>x.Remark,
                x=>x.Icon,
                x=>x.Url);
            return await SaveChangesAsync();
        }

        public async Task<int> Delete(Domain.Entities.System.Application[] entityies)
        {
            var ids = entityies.Select(x => x.Id).ToList();
            await LogicRemove(new DirectSpecification<Domain.Entities.System.Application>(x => ids.Contains(x.Id)));
            return await SaveChangesAsync();
        }
    }
}
